import { AppRoute, LoginParams, RefreshTokenParam } from "@scpun/core";
import { httpClient } from "../http";

const URL = {
    OAUTH2_TOKEN: "/mock-api/oauth2/token",
    CHECK_TOKEN: `/mock-api/oauth2/check_token`,
    OAUTH2_REVOKE: `/mock-api/oauth2/revoke`,
    OAUTH2_ROUTE: "/mock-api/oauth2/routes",
};

const BASIC_AUTHORIZATION = "Basic aGVybWVzLWRpYWdub3N0aWM6aGVybWVzLWRpYWdub3N0aWMtc2VjcmV0";

function login(params: LoginParams) {
    return httpClient.post(
        URL.OAUTH2_TOKEN,
        {},
        {
            params,
            headers: {
                Authorization: BASIC_AUTHORIZATION,
            },
        }
    );
}

export function loadByUsername(params: LoginParams) {
    !params.grant_type && (params.grant_type = "password");
    !params.scope && (params.scope = "all");
    return login(params);
}

export const refreshToken = (refreshToken: string) => {
    const params: RefreshTokenParam = {
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        scope: "all",
    };
    return httpClient.post(URL.OAUTH2_TOKEN, params, {
        // params,
        headers: {
            Authorization: BASIC_AUTHORIZATION,
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
        },
    });
};

export function checkToken(token: string) {
    return httpClient.post(
        URL.CHECK_TOKEN,
        {},
        {
            headers: {
                Authorization: BASIC_AUTHORIZATION,
            },
            params: {
                token,
            },
        }
    );
}

export function logout(token?: string) {
    return httpClient.post(
        URL.OAUTH2_REVOKE,
        {},
        {
            headers: {
                Authorization: BASIC_AUTHORIZATION,
            },
            params: {
                token,
            },
        }
    );
}

export function getUserRoutes() {
    return httpClient.get<AppRoute[]>(URL.OAUTH2_ROUTE);
}
